package com.bw.controller;

import com.alibaba.fastjson.JSONObject;
import com.bw.aop.GiteeUtils2;
import com.bw.entity.User;
import com.bw.mapper.UserMapper;
import org.apache.poi.ss.formula.functions.T;
import org.spring.kun.common.TokenUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletResponse;
import java.util.SortedMap;

@Controller
public class GiteeLoginController {

    @Autowired
    UserMapper userMapper;

    @RequestMapping("/loginPage.do")
    public String loginPage(){

        return "login";
    }

    @RequestMapping("/callbackCode.do")
    public String callbackCode(String code, HttpServletResponse response){
        System.out.println("接收到的临时授权码 " + code);
        String tokenByCode = GiteeUtils2.getAccessTokenByCode(code);

        JSONObject userInfoByToken = GiteeUtils2.getGiteeUserInfoByToken(tokenByCode);

        System.out.println("获取到的用户 " + JSONObject.toJSONString(userInfoByToken));

        String name = userInfoByToken.getString("login");
        String nickName = userInfoByToken.getString("name");
        String avatarUrl = userInfoByToken.getString("avatar_url");
        Integer giteeId = userInfoByToken.getInteger("id");
        // 注册一个新用户

        User user = new User();
        user.setGiteeId(giteeId);
        user.setName(name);
        user.setNickName(nickName);
        user.setAvatarUrl(avatarUrl);

        userMapper.addUser(user);
        // 加密用户信息
        TokenUtils.responseTokenByCookie(user,response,30);
        return "redirect:list.do";
    }
}
